const {Result, GlobalPaths} = require("../core/basic");
const IOSystem = require("./io_system");
const Utils = require("./utils");
const Log = require("../core/logger");

let users = new Map();

class User {
    constructor(id, p) {
        Utils.CreateProperty(this, "_id", id, false, false, false);
        Utils.CreateProperty(this, "_pwd", p, false, false, false);
        this._displayName = "";
    }

    Check(pwd) {
        return this._pwd === pwd;
    }
}

let Init = function () {
    const _userFileURL = GlobalPaths.ROOT_SERVER + "users.json";
    if(!IOSystem.FileExist(_userFileURL)) {
        Log.Error("There is NO user config file!");
        return;
    }

    let _config = JSON.parse(IOSystem.ReadFileUTF8(_userFileURL));
    for(let i = 0, N = _config.users.length; i < N; ++i) {
        const _tmp = _config.users[i];
        let _acc = new User(_tmp.id, _tmp.password);
        _acc.displayName = _tmp.displayName;
        users.set(_acc.id, _acc);
    }
}()

module.exports.GetAccountDisplayName = function (id, out) {
    let _u = users.get(id);
    if(_u) {
        out.data = _u.displayName;
        return Result.OK;
    } else {
        out.msg = `user(${id}) NOT exist.`;
        return Result.ACCOUNT_NOT_EXIST;
    }
}

module.exports.CheckAccount = function (id, pwd) {
    let _u = users.get(id);
    if(_u) {
        if(_u.Check(pwd)) {
            return Result.OK;
        } else {
            return Result.PASSWORD_ERROR;
        }
    } else {
        return Result.ACCOUNT_NOT_EXIST;
    }
}

